package com.mengniu.commerce.sync.utils;

import com.alibaba.fastjson.JSONObject;
import com.mengniu.commerce.common.core.enums.ModuleEnum;
import com.mengniu.commerce.common.core.utils.IdGeneratorSnowflake;
import com.mengniu.commerce.common.template.enums.APIUrlEnum;
import com.mengniu.commerce.sync.mapper.RetryMapper;
import com.mengniu.commerce.sync.model.RetryModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

@Component
public class RetryUtils {

    @Resource
    private RetryMapper retryMapper;


    public Long insert (JSONObject param, String source, String storeName, String moduleName, String retryType, Integer retryNum, String errorReason){
        RetryModel retryModel = new RetryModel();
        long id = new IdGeneratorSnowflake().snowflakeId();
        retryModel.setId(id);
        retryModel.setParams(param.toJSONString());
        retryModel.setSource(source);
        retryModel.setStoreName(storeName);
        retryModel.setModuleName(moduleName);
        retryModel.setRetryType(retryType);
        retryModel.setRetryNum(retryNum);
        retryModel.setErrorReason(errorReason);
        retryModel.setCreateTime(new Date());
        retryMapper.insert(retryModel);
        return id;
    }

    public void update(Long id,Integer retryNum,String errorReason){
        RetryModel retryModel = retryMapper.selectVoById(id);
        if (Optional.ofNullable(retryModel).isPresent()){
            return;
        }
        retryModel.setRetryNum(retryNum);
        retryModel.setErrorReason(errorReason);
        retryModel.setUpdateTime(new Date());
        retryMapper.updateById(retryModel);
    }


    public Long insertOrUpdate(JSONObject param, String source, String storeName, String moduleName, String retryType, Integer retryNum, String errorReason,Long id){
        if (retryNum == 0 && Objects.isNull(id)) {
            id = this.insert(param, source, storeName, moduleName, retryType, retryNum,errorReason);
        }else {
            this.update(id,retryNum,errorReason);
        }
        return id;
    }







}
